<?php
/**
 * 红包游戏
 * User: admin
 * Date: 2017/7/11
 * Time: 16:26
 */
session_start();
class Model_RedBagGame extends Model_Common {


    /**
     * 发布红包游戏
     * @desc 创建红包任务
     */
    public function addRedgame($uid,$liveid,$title,$num,$money){

        $user=DI()->notorm->users
            ->select("coin")
            ->where('id=?',$uid)
            ->fetchOne();
        if($money > $user['coin']){
            return 1002; //用户余额不足
        }
        if($num<2){
            return 1003; //人数不足
        }
        $mine = DI()->notorm->redratio->where('id=1')->fetchOne();
        $minute=$mine['returnred_time'];
        $data=array(
            'uid'=>$uid,
            'title' => $title,
            'num' => $num,
            'money' =>$money,
            'uptime' =>time(),
            'createtime' =>time(),
            'liveid' =>$liveid,
            'deadline' =>strtotime('+'.$minute.' minute')
        );

         //创建红包任务
        $rs=DI()->notorm->red_task->insert($data);
        $data2=array(
            'task_id' => $rs['id'],
            'uid'=>$uid,
            'status' => 1,
            'paymoney' =>$money,
            'drawmoney' => 0,
            'uptime' =>time(),
            'liveid' =>$liveid
        );
        //参加红包任务
        $re=DI()->notorm->par_task->insert($data2);
        if($re){
            $updata= array(
                'already_num' => new NotORM_Literal("already_num +1"),
                'already_money' =>  new NotORM_Literal("already_money +{$money}"),
                'uptime' => time()
            );
            //更新参加人数和参与金额
            DI()->notorm->red_task
                ->where('id = ?', $rs['id'])
                ->update($updata);
        }

        if($rs){
            //用户相应减去金额
            DI()->notorm->users
                ->where('id = ?', $uid)
                ->update(array('coin' => new NotORM_Literal("coin - {$money}")) );
            //消费记录
            $record['coin'] =$money;
            $record['type'] = 1;
            $record['uid'] = $uid;
            $record['task_id']=$rs['id'];
            $record['uptime'] = time();
            $r=DI()->notorm->record->insert($record);
            return 0;
        }else{
            return 1001;
        }

    }

    /**
     * 参与红包游戏
     * @desc 参与红包任务
     * @return int code 操作码，0表示成功
     * @return string msg 提示信息
     */
    public function parRedgame($uid,$liveid,$task_id)
    {
        $task = DI()->notorm->red_task
            ->select("num,already_num,money,already_money")
            ->where('id=?', $task_id)
            ->fetchOne();
        if ($task['num'] == $task['already_num']){ //总人数和已支付人数
            return 1001;
        }

        if($task['status'] == 2){ //拼福失败
            return 1004;
        }


        $user=DI()->notorm->users
            ->select("coin")
            ->where('id=?',$uid)
            ->fetchOne();
        if($task['money'] > $user['coin']){
            return 1003; //用户余额不足
        }

        $where['task_id'] =$task_id;
        $where['uid'] = $uid;
        $res = DI()->notorm->par_task
            ->select("task_id,uid")
            ->where($where)
            ->fetchOne();
        if($res){
            return 1002;  //已参与
        }

        $money =$task['money'];
        $data2 = array(
            'task_id' => $task_id,
            'uid' => $uid,
            'status' => 1,
            'paymoney' => $money,
            'drawmoney' => 0,
            'uptime' => time(),
            'liveid' => $liveid
        );
        //参加红包任务
        $re = DI()->notorm->par_task->insert($data2);
        if ($re) {
            $updata = array(
                'already_num' => new NotORM_Literal("already_num +1"),
                'already_money' => new NotORM_Literal("already_money +{$money}"),
                'uptime' => time()
            );

            //更新参加人数和参与金额
            DI()->notorm->red_task
                ->where('id = ?', $task_id)
                ->update($updata);
            //用户相应减去金额
            $r=DI()->notorm->users
                ->where('id = ?', $uid)
                ->update(array('coin' => new NotORM_Literal("coin - {$money}")));
            //消费记录
            $record['coin'] =$money;
            $record['type'] = 1;
            $record['uid'] = $uid;
            $record['task_id']=$task_id;
            $record['uptime'] = time();
            $r=DI()->notorm->record->insert($record);
            //已满足人数，分红包，更新状态
            $result=DI()->notorm->red_task->where('num=already_num and id=?',$task_id)->fetchOne();
            if($result){
                $up_data=array(
                    'status' =>1,
                    'uptime' => time()
                );
                DI()->notorm->red_task
                    ->where('id = ?', $task_id)
                    ->update($up_data);

                $task = DI()->notorm->red_task
                    ->select("num,already_num,money,already_money")
                    ->where('id=?', $task_id)
                    ->fetchOne();
                $par_task = DI()->notorm->par_task->where('task_id=?',$task_id)->fetchAll();
                $totalmoney =$task['already_money'];
                $zong_money=$task['money']*$task['num'];

                $ratio = DI()->notorm->redratio->fetchOne();
                if($ratio['status']==1){
                    $totalmoney=$totalmoney-$zong_money*$ratio['ratio']/100;
                }
                $num =DI()->notorm->par_task->where('drawmoney =0 and  task_id=?',$task_id)->count();
                $moneys = $this->randomPenny($totalmoney,$num);
                $n=1;
                foreach ($par_task as $key=>$par){
                    $par_data=array();
                    if($par['drawmoney']>0){
                        $par_data = array(
                            'status' => 2,
                            'uptime' => time()
                        );
                    }else{
                        $drawmoney=$moneys[$n];
                        if($drawmoney ==0){
                            $drawmoney="0.01";
                        }
                        $par_data = array(
                            'drawmoney' =>$drawmoney ,
                            'status' => 2,
                            'uptime' => time()
                        );
                        $n++;
                    }
                    $map['uid']=$par['uid'];
                    $map['task_id']=$task_id;
                  DI()->notorm->par_task->where($map)->update($par_data);
                }
            }
            return 0;
        };

    }

    /**
     * 未参与红包游戏列表
     * @desc 未参与红包游戏列表
     * @return int code 操作码，0表示成功
     */
    public function  redGamelist($uid,$liveid){

       $where['liveid'] =$liveid;
       $where['status'] = 0;
        $res = DI()->notorm->red_task
            ->where($where)
            ->order('uptime desc')
            ->fetchAll();
        foreach ($res as $k=>&$re){
            $task = DI()->notorm->par_task
                ->where('uid=?', $uid)
                ->where(' task_id=?',$re['id'])
                ->fetchOne();
            if($task){
                unset($res[$k]);
            }else {
                $users = DI()->notorm->users
                    ->where('id=?', $re['uid'])
                    ->fetchOne();
                $res[$k]['avatar'] = $users['avatar'];
            }
        }
        //sort($res);
        $res =array_merge($res);
        return $res;

    }

    /**
     * 已参与红包游戏列表
     * @desc 已参与红包游戏列表
     * @return int code 操作码，0表示成功
     * @return string msg 提示信息
     * status 1,进行中 2，未拆开，3，退款中 4，已拆开 5，已退款
     */
    public  function haveGamelist($uid,$liveid,$type){

        if($type == 1){ //进行中
            $where['status']=1;
        }else if($type == 2){ //未拆开
            $where['status']=2;
        }else if($type == 3){ //退款中
            $where['status']=3;
        }else if($type == 4){  //已拆开
            $where['status']=4;
        }else if($type == 5){ //已退款
            $where['status']=5;
        }
        $map['liveid'] = $liveid;
        $res = DI()->notorm->red_task
            //->select("task_id,uid,drawmoney,status")
            ->where($map)
            ->order('uptime desc')
            ->fetchAll();

        foreach ($res as $k=>&$re){
            $task = DI()->notorm->par_task
                ->where('uid=?', $uid)
                ->where(' task_id=?',$re['id'])
                ->where($where)
                ->fetchOne();
            $re['status'] = $task['status'];
            $re['drawmoney'] = $task['drawmoney'];
            if(!$task){
                unset($res[$k]);
            }else {
                $users = DI()->notorm->users
                    ->where('id=?', $re['uid'])
                    ->fetchOne();
                $res[$k]['avatar'] = $users['avatar'];
            }
        }
        $res =array_merge($res);

        return $res;
    }

    /**
     * 已参与红包任务详情
     * @desc 红包任务详情
     * @return int code 操作码，0表示成功
     * @return string msg 提示信息
     * @request status 1,进行中 2，未拆开，3，退款中 4，已拆开 5，已退款
     */
    public function  reddetails($uid,$status,$task_id){
        $msg='';
        $task = DI()->notorm->red_task->where('id=?',$task_id)->fetchOne();
        $map2['uid'] =$uid;
        $map2['task_id'] =$task_id;
        $partask = DI()->notorm->par_task->where($map2)->fetchOne();

        if($status ==1){ //进行中
            $msg="支付".$task['money']."播豆参加，已参加".$task['already_num']."人，满".$task['num']."人送福。";
        }else if($status == 2){ //未拆开
            $msg = "恭喜您，您参与的游戏红包活动，获得红包".$partask['drawmoney']."播豆。";
             $map['status'] =4;
             $map['uptime']=time();
             $where['uid'] =$uid;
             $where['task_id'] =$task_id;
            $partask1 = DI()->notorm->par_task->where($where)->update($map);
            //用户相应加上金额
            $r=DI()->notorm->users
                ->where('id = ?', $uid)
                ->update(array('coin' => new NotORM_Literal("coin + {$partask['drawmoney']}")));
            //消费记录
            $record['coin'] =$partask['drawmoney'];
            $record['type'] = 2;
            $record['uid'] = $uid;
            $record['task_id']=$task_id;
            $record['uptime'] = time();
            $r=DI()->notorm->record->insert($record);
        }else if ($status == 3){ //退款中
            $msg="退款成功！退款".$partask['paymoney']."播豆";
            //用户相应加上金额
            $r=DI()->notorm->users
                ->where('id = ?', $uid)
                ->update(array('coin' => new NotORM_Literal("coin + {$partask['paymoney']}")));
            //消费记录
            $record['coin'] =$partask['paymoney'];
            $record['type'] = 3;
            $record['uid'] = $uid;
            $record['task_id']=$task_id;
            $record['uptime'] = time();
            $r=DI()->notorm->record->insert($record);
            $map3['status'] =5;
            $map3['uptime']=time();
            $partask = DI()->notorm->par_task->where($map2)->update($map3);
        }else if ($status == 4){ //已拆开
            $draw=DI()->notorm->par_task->where('uid=?',$uid)->fetchOne();
            $msg = "您参与的游戏红包活动，已获得红包".$partask['drawmoney']."播豆。";
        }else if($status == 5){ //已退款
            $msg="您参与的游戏红包活动已成功退款".$task['money']."播豆";
        }
        $par_task = DI()->notorm->par_task->where('task_id=?',$task_id)->fetchAll();
        foreach ($par_task as &$par){
            $user=$this->getUserInfo($par['uid']);
            $par['nickname']=$user['user_nicename'];
            $par['avatar_thumb']   =$user['avatar_thumb'];
            $par['uptime'] = date('Y-m-d H:i:s', $par['uptime']);
        }
        $data['msg']=$msg;
        $data['title'] =$task['title'];
        $data['type'] = $status;
        $data['partask'] =$par_task;
        return $data;
    }

    /**
     * 随机分红包
     * @param $total 总金额
     * @param $num 人数
     * @param float $min 最小值
     * @return string
     */
    public function  randomPenny($total,$num,$min=1){
        $data=array();
        for($i=1;$i<$num;$i++){
            //随机安全上限
            $safe_total=($total-($num-$i)*$min)/($num-$i);
            //金额
            $money=mt_rand($min,$safe_total);
            //$money=mt_rand($min*100,$safe_total*100);
            $total=$total-$money;
            $data[$i]=$money;
        }
        $data[$num] =$total;
        return $data;
    }

    /**
     * 未参与红包任务详情
     * @desc 未参与红包任务详情
     * @return int code 操作码，0表示成功
     * @return string msg 提示信息
     */
    public function noReddetails($uid,$task_id){
        $msg='';
        $task = DI()->notorm->red_task->where('id=?',$task_id)->fetchOne();
        if($task['status'] == 1){
            if($task['num'] == $task['already_num']){
                $msg="支付".$task['money']."播豆参加，已参加".$task['already_num']."人，满".$task['num']."人送福，任务已完成，正在瓜分";
                $type=1;
            }
        }else if ($task['status'] == 2){
            $msg  = "拼福运失败，已参加".$task['already_num']."人，金额原数退回。";
            $type = 3;
        }else{
            $msg="支付".$task['money']."播豆参加，已参加".$task['already_num']."人，满".$task['num']."人送福。";
            $type=2;
        }
        $partask = DI()->notorm->par_task->where('task_id=?',$task_id)->fetchAll();
        foreach ($partask as &$par){
            $user=$this->getUserInfo($par['uid']);
            $par['nickname']=$user['user_nicename'];
            $par['avatar_thumb']   =$user['avatar_thumb'];
            $par['uptime'] = date('Y-m-d H:i:s', $par['uptime']);
            if($par['status'] ==2) {
                $par['money_txt'] = $par['drawmoney'] . "播豆";
            }
            if($par['status'] ==5){
                $par['money_txt'] ="已退款".$par['paymoney']."播豆";
            }
        }
        $data['msg']=$msg;
        $data['title'] =$task['title'];
        $data['type'] = $type;
        $data['partask'] =$partask;
        return $data;

    }

    /**
     * 退款
     * @desc 退款
     * @return int code 操作码，0表示成功
     * @return string msg 提示信息
     */
    public function refund($uid,$task_id){
        $task = DI()->notorm->red_task->where('id=?',$task_id)->fetchOne();
        $partask = DI()->notorm->par_task->where('task_id=?',$task_id)->where('uid=?',$uid)->fetchOne();
        if($task['status']==0 && $partask['status'] == 1){
            $money = $task['already_money']-$partask['paymoney'];
            $num  = $task['already_num'] - 1;
            $map['already_money'] = $money;
            $map['already_num']   = $num;
            $res = DI()->notorm->red_task->where('id=?',$task_id)->update($map);
            if($res){
                DI()->notorm->par_task->where('task_id=?',$task_id)->where('uid=?',$uid)->delete();
                $tasks = DI()->notorm->red_task->where('id=?',$task_id)->fetchOne();
                if($tasks['already_num'] == 0){
                    DI()->notorm->red_task->where('id=?',$task_id)->delete();
                }
                //用户相应加上金额
                $r=DI()->notorm->users
                    ->where('id = ?', $uid)
                    ->update(array('coin' => new NotORM_Literal("coin + {$money}")));
                //消费记录
                $record['coin'] =$money;
                $record['type'] = 3;
                $record['uid'] = $uid;
                $record['task_id']=$task_id;
                $record['uptime'] = time();
                $r=DI()->notorm->record->insert($record);
                return  10000;
            }
        }else{
            return 10001;
        }
    }

    /**
     * 红包收益
     * @desc 红包收益
     * @return int code 操作码，0表示成功
     * @return string msg 提示信息
     */
    public function redProfit($uid){
        $insert = DI()->notorm->record->select("sum(coin) as coin")->where('uid=?',$uid)->where('type=1')->fetchOne();

        $get    = DI()->notorm->record->select("sum(coin) as coin")->where('uid=?',$uid)->where("type in ('2','3')")->fetchOne();

        $record = DI()->notorm->record->where('uid=?',$uid)->order('uptime desc')->fetchAll();

        $profit=$get['coin']-$insert['coin'];
        $insert = $insert['coin']?$insert['coin']:0;
        $get = $get['coin']?$get['coin']:0;

        $data['get']=number_format($get,2);;
        $data['insert']=number_format($insert,2);;
        $data['profit']=number_format($profit,2);
        foreach ($record as &$rec){
            if($rec['type'] ==1){
                $rec['type_txt'] ="投入";
                $rec['coin_txt'] ="-".$rec['coin'];
            }else if($rec['type'] ==2){
                $rec['type_txt'] = "获得";
                $rec['coin_txt'] ="+".$rec['coin'];
            }else if($rec['type'] ==3){
                $rec['type_txt'] = "退款";
                $rec['coin_txt'] ="+".$rec['coin'];
            }
        }
        $data['record'] = $record?$record:array();
        return $data;
    }

    /**
     * 红包规则
     * @desc 红包规则
     * @return int code 操作码，0表示成功
     * @return string msg 提示信息
     */
    public function redrule(){
        $rule = DI()->notorm->redrule->fetchOne();;
        $data['content'] =$rule['content'];
        return $data;
    }

    /**
     * 我要参加我的余额
     * @desc 我的余额
     * @return int code 操作码，0表示成功
     * @return string msg 提示信息
     */
    public function  mybalance($uid,$task_id){
        $user = DI()->notorm->users->where('id='.$uid)->fetchOne();
        $red  = DI()->notorm->red_task->where('id='.$task_id)->fetchOne();
        $data['balance'] =$user['coin'];
        $data['paymoney'] =$red['money'];
        return $data;
    }


    /**
     * 发起任务，我的余额
     * @desc 我的余额
     * @return int code 操作码，0表示成功
     * @return string msg 提示信息
     */
    public function  mybalance2($uid){
        $user = DI()->notorm->users->where('id='.$uid)->fetchOne();
      //  $red  = DI()->notorm->red_task->where('id='.$task_id)->fetchOne();
        $data['balance'] =$user['coin'];
      //  $data['paymoney'] =$red['money'];
        return $data;
    }
}